package com.zxt.lock;

import com.zxt.lock.annotation.DistributedLock;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author zxt
 */
public class RedissonLock {
    private static final Logger log = LoggerFactory.getLogger(RedissonLock.class);
    private RedissonManager redissonManager;

    /**
     * 获取分布式锁
     *
     * @param lockName  锁名称
     * @param waitTime  最大等待时间
     * @param leaseTime 锁占用时间
     * @return
     */
    public boolean lock(String lockName, long waitTime, long leaseTime) {
        RLock rLock = this.redissonManager.getRedisson().getLock(lockName);
        boolean getLock = Boolean.FALSE;

        try {
            getLock = rLock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
            if (getLock) {
                log.info("获取Redisson分布式锁[成功],lockName={}", lockName);
            } else {
                log.info("获取Redisson分布式锁[失败],lockName={}", lockName);
            }
            return getLock;
        } catch (InterruptedException var9) {
            log.error("获取Redisson分布式锁[异常]，lockName=" + lockName, var9);
            return Boolean.FALSE;
        }
    }

    public void release(String lockName) {
        RLock lock = this.redissonManager.getRedisson().getLock(lockName);
        if (!Objects.isNull(lock)) {
            lock.unlock();
        }
    }

    public RedissonLock(final RedissonManager redissonManager) {
        this.redissonManager = redissonManager;
    }

    public RedissonLock() {
    }

    public RedissonManager getRedissonManager() {
        return this.redissonManager;
    }

    public void setRedissonManager(final RedissonManager redissonManager) {
        this.redissonManager = redissonManager;
    }
}
